package biz_db

import (
	"encoding/json"
	"fmt"
	"time"
)

type UserDao interface {
	Create()
	Update()
	Delete()
	Select()
}

type UserService struct {
}

func (u UserService) Create() {
	now := time.Now()
	user := User{Name: "Jinzhu", Age: 18, Birthday: &now}

	result := db.Create(&user) // pass pointer of data to Create

	fmt.Println("user.ID", user.ID, result.Error, result.RowsAffected)

	db.Select("Name", "Age", "CreatedAt").Create(&user)
	// INSERT INTO `users` (`name`,`age`,`created_at`) VALUES ("jinzhu", 18, "2020-07-04 11:05:21.775")
}

func (u UserService) Update() {
	// https://gorm.io/docs/update.html
	user := &User{ID: 1}
	db.First(user)

	user.Name = "jinzhu 2"
	user.Age = 100
	db.Save(&user)
	// UPDATE users SET name='jinzhu 2', age=100, birthday='2016-01-01', updated_at = '2013-11-17 21:34:10' WHERE id=111;

}

func (u UserService) Delete() {
	user := &User{ID: 1}
	db.Delete(user)
}

func (u UserService) Select() {
	result := make([]User, 1, 10)
	db.Model(&User{}).Limit(10).Find(&result, "name like ?", "%2%")

	for i, v := range result {
		fmt.Println("结果", i, v)
		jsonByte, _ := json.Marshal(v)
		fmt.Println("结果json化", string(jsonByte))
	}

}
